package com.wl.api.controller;

import java.util.Objects;
import java.util.function.Predicate;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.wl.api.common.annotation.RequiresAuthentication;
import com.wl.api.common.result.LoginUserBean;
import com.wl.api.common.utils.ErrorCodeEnum;
import com.wl.api.common.utils.JsonObject;
import com.wl.api.common.utils.ObjectUtil;
import com.wl.api.common.utils.StringUtil;
import com.wl.api.common.utils.constant.AppEnum;
import com.wl.api.controller.base.CommonController;
import com.wl.api.dto.base.CommonUserDTO;
import com.wl.api.dto.business.CustomerUserDTO;
import com.wl.api.dto.system.SecurityUserDTO;
import com.wl.api.model.business.CustomerUser;
import com.wl.api.service.business.ICustomerUserService;
import com.wl.api.service.system.ISecurityRolePermissionService;
import com.wl.api.service.system.ISecurityRoleService;
import com.wl.api.service.system.ISecurityUserService;

@RestController
public class LoginController extends CommonController {
    @Autowired
	ISecurityUserService userService;
    @Autowired
    ICustomerUserService customerUserService;
    @Autowired
    ISecurityRoleService roleService;
	
	@RequestMapping(value ="/login", method=RequestMethod.POST)
	@RequiresAuthentication(getClientType= AppEnum.anonymity_client)
	public JsonObject login(LoginUserBean formbean) {
		JsonObject json = JsonObject.getInstance();
		boolean pass = true;
		String title = "" , code = "";
		CustomerUser customer = null;
		SecurityUserDTO securityUser = null;
		CommonUserDTO commonUser;
		if (validate().test(formbean)) {
			pass = false;
			code = ErrorCodeEnum.login_fail_param_error.getError_code();
			title = ErrorCodeEnum.login_fail_param_error.getMessage();
		}
		if (pass) {
			if (CUSTOMER_CLIENT_ID.equals(formbean.getClientId())) {
				customer = customerUserService.getCustomerUser(CustomerUserDTO.builder().username(formbean.getUsername()).password(DigestUtils.md2Hex(formbean.getPassword())).isDeleted(0).build());
				if (Objects.isNull(customer)) {
					pass =false; 
				} 
			}
			if (pass && ADMIN_CLIENT_ID.equals(formbean.getClientId())) {
				securityUser = userService.getUserMessage(SecurityUserDTO.builder().username(formbean.getUsername()).password(DigestUtils.md2Hex(formbean.getPassword())).isDeleted(0).build());
				if (ObjectUtil.isEmpty(securityUser)) {
					pass =false; 
				}
			}

			if (!pass) {
				code = ErrorCodeEnum.login_fail_account_error.getError_code();
				title = ErrorCodeEnum.login_fail_account_error.getMessage();
			}
		}
		if (pass) {
			if (ADMIN_CLIENT_ID.equals(formbean.getClientId())) {
				commonUser = CommonUserDTO.builder().clientId(formbean.getClientId()).custId(securityUser.getId()).id(securityUser.getId()).email(securityUser.getEmail()).username(securityUser.getUsername()).realname(securityUser.getRealname()).phone(securityUser.getPhone())
							.snList(userService.getUserPermission(securityUser.getId())).roleName(roleService.getRoleNameByUserID(securityUser.getId())).build();
			} else {
				commonUser = CommonUserDTO.builder().clientId(formbean.getClientId()).custId(customer.getCustId()).id(customer.getCustId()).email(customer.getEmail()).username(customer.getUsername()).realname(customer.getRealname()).phone(customer.getPhone()).address(customer.getAddress()).countryId(customer.getCountryId()).headImgs(customer.getHeadImgs()).build();
			}
			String access_token = StringUtil.getUUID();
			addAccessCache(access_token, commonUser);
			json.setData(access_token);
		}
		
		setJsonMessage(json, title, code,  pass);
		return json;
	}
	
	@RequestMapping("/userInfo")
	public JsonObject getUserInfo() throws Exception {
		JsonObject json = JsonObject.getInstance();
		CommonUserDTO user = getCommonUser();
		user.setSnList(null);
		json.setData(user);
		return json;
	}
	
	private Predicate<LoginUserBean> validate() {
		return s -> StringUtil.isEmpty(s.getClientId()) || StringUtil.isEmpty(s.getPassword())
				|| StringUtil.isEmpty(s.getUsername()) || (!ADMIN_CLIENT_ID.equals(s.getClientId())) && !CUSTOMER_CLIENT_ID.equals(s.getClientId());
	}
}
